package com.intct.flink;

import com.intct.hbase.bean.User;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @author gufg
 * @since 2025-06-25 10:40
 */
public class FromKafkaGetData {
    public static void main(String[] args) throws Exception {
        // 创建环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        // 获取数据源
        KafkaSource<String> source = KafkaSource.<String>builder()
                .setBootstrapServers("jd-node:9092")  // 连接的kafka
                .setTopics("my-topic")
                .setGroupId("my-group")
                // earliest 从最早消费  which initializes the offsets to the earliest available offsets of each
                /**
                 * kafka消费者的参数：
                 * auto.reset.offsets
                 * earliest:如果没有offset，从 最早 消费
                 * latest :如果没有offset，从 最新 消费
                 *
                 * flink的kafkasource，offset消费策略：OffsetsInitializer，默认是 earliest
                 * earliest: 从 最早 消费(和有无offset无关)
                 * latest : 从 最新 消费(和有无offset无关)
                 */
                /**
                 // 从消费组提交的位点开始消费，不指定位点重置策略
                 .setStartingOffsets(OffsetsInitializer.committedOffsets())
                 // 从消费组提交的位点开始消费，如果提交位点不存在，使用最早位点
                 .setStartingOffsets(OffsetsInitializer.committedOffsets(OffsetResetStrategy.EARLIEST))
                 // 从时间戳大于等于指定时间戳（毫秒）的数据开始消费
                 .setStartingOffsets(OffsetsInitializer.timestamp(1657256176000L))
                 // 从最早位点开始消费
                 .setStartingOffsets(OffsetsInitializer.earliest())
                 // 从最末尾位点开始消费
                 .setStartingOffsets(OffsetsInitializer.latest());
                 */
                .setStartingOffsets(OffsetsInitializer.latest())
                // 指定值 的反序列化器
                .setValueOnlyDeserializer(new SimpleStringSchema())
                .build();

        DataStreamSource<String> kafkaDS =
                env.fromSource(source, WatermarkStrategy.noWatermarks(), "kafka-source");

        // Map算子转换
        SingleOutputStreamOperator<User> mapDS = kafkaDS.map(new MapFunction<String, User>() {
            @Override
            public User map(String value) throws Exception {
                // 1 zhangsan password
                String[] valueSplit = value.split(" ");
                User user = new User();
                user.setId(Integer.parseInt(valueSplit[0]));
                user.setName(valueSplit[1]);
                user.setPassword(valueSplit[2]);

                return user;
            }
        });

        // Filter算子转换
        SingleOutputStreamOperator<User> filterDS = mapDS.filter(new FilterFunction<User>() {
            @Override
            public boolean filter(User user) throws Exception {
                if (user.getName().equals("lisi")) {
                    return false;
                } else {
                    return true;
                }
            }
        });

        // 表达式方
        SingleOutputStreamOperator<User> filterDS1 = mapDS.filter(f -> !f.getName().equals("lisi"));

        // flatMap算子转换
        SingleOutputStreamOperator<Tuple2<String, Integer>> flatMapDS = kafkaDS.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                String[] flatMapSplit = value.split(" ");
                for (String str : flatMapSplit) {
                    out.collect(Tuple2.of(str, 1));
                }
            }
        });

        // 输出
        flatMapDS.print();

        // 启动作业
        env.execute();
    }
}
